<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import wjzs from '@/components/wjzs.vue'
import { useRoute } from 'vue-router'
import wsjzglService from '@/api/wsjzgl'
import printFn from '@/utils/print'

const route = useRoute()
// ref
const wjzsRef = ref<InstanceType<typeof wjzs>>()
/*
 * 打开弹框
 */

const dialogVisible = ref(false)
const openDialog = () => {
  dialogVisible.value = true
  getUrlTgspb()
}

const url = ref()
const getUrlTgspb = () => {
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    gdbh: route.query.gdbh as unknown as string,
  }
  wsjzglService
    .getZzml(params)
    .then((res: any) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        url.value = window.URL.createObjectURL(res.data)
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
// 下载按钮
const download = () => {
  const downloadElement = document.createElement('a')
  downloadElement.href = url.value
  downloadElement.download = '纸质目录.pdf'
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
}

const print = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '纸质目录.pdf',
    loadingHeader: {},
    loadingParam: {
      bmsah: route.query.bmsah as string,
      gdbh: route.query.gdbh as string,
    },
    loadingUrl: `${window.IPCONFIG}/api/wsjzgl/getZzml`,
    requestMethodName: 'POST',
  }
  printFn(params)
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="纸质目录" width="70%" :close-on-click-modal="false">
    <div class="dialog-box">
      <!--文件-->
      <wjzs ref="wjzsRef" wjlx="pdf" :url="url" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="download">下载</el-button>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 70vh;
}
</style>
